package com.example.smartcity.fragment;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smartcity.R;
import com.example.smartcity.activity.AdviceContentActivity;
import com.example.smartcity.activity.NewsWebViewActivity;
import com.example.smartcity.bean.AdviceBean;
import com.example.smartcity.bean.NewsBean;
import com.example.smartcity.utils.APIConfig;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class JActivityFragment extends BaseFragment {
    ListView jd_activity_lv;
    private AdviceBean adviceBean;
    String result;
    private static final String TAG = JActivityFragment.class.getSimpleName();
    @Override
    public View initView() {
        Log.i(TAG,"疑问展示");
        View view = View.inflate(getActivity(),R.layout.jd_activity,null);
        jd_activity_lv = view.findViewById(R.id.jd_activity_list);
        getAdviceData(true);
        Button refreshButton = view.findViewById(R.id.refresh_button);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getAdviceData(true);
            }
        });

        return view;
    }
    public void initData() {
        super.initData();
    }

    private void getAdviceData(boolean isRefresh) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(APIConfig.BASE_URL + "/getalladvice")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("onFailure",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    result = response.body().string();
                    Log.i("Advice_Request_Success:",result);
                    Gson gson = new Gson();
                    adviceBean =  gson.fromJson(result, AdviceBean.class);

                    Log.i("advice", adviceBean.getAdviceList().toString());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AdviceAdapter adviceAdapter = new AdviceAdapter();
                            jd_activity_lv.setAdapter(adviceAdapter);
                            //setListViewHeightBasedOnChildren(jd_activity_lv);
                            if (isRefresh) {
                                adviceAdapter.notifyDataSetChanged();
                            } else {
                                adviceAdapter.addData(adviceBean.getAdviceList());
                            }

                            jd_activity_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Intent intent = new Intent(getActivity(), AdviceContentActivity.class);
                                    intent.putExtra("username",adviceBean.getAdviceList().get(i).getUsername());
                                    intent.putExtra("content",adviceBean.getAdviceList().get(i).getAdviceContent());
                                    intent.putExtra("reply",adviceBean.getAdviceList().get(i).getReply());
                                    getActivity().startActivity(intent);
                                }
                            });

                        }
                    });
                }
            }
        });
    }

    public class AdviceAdapter extends BaseAdapter {
        private List<AdviceBean.Advice> adviceList;

        public AdviceAdapter() {
            adviceList = new ArrayList<>();
        }

        public void addData(List<AdviceBean.Advice> data) {
            adviceList.addAll(data);
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            return adviceBean!=null ? adviceBean.getAdviceList().size() : 0;
        }
        @Override
        public Object getItem(int i) {
            return adviceBean.getAdviceList().get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            JActivityFragment.AdviceAdapter.ViewHolder holder;
            if (view==null) {
                view = View.inflate(getContext(), R.layout.advice_item,null);
                holder = new ViewHolder();
                holder.username = view.findViewById(R.id.advicer_username);
                holder.advice_context = view.findViewById(R.id.advice_context);
                holder.advice_reply = view.findViewById(R.id.advice_reply);


                view.setTag(holder);
            } else {
                holder = (AdviceAdapter.ViewHolder) view.getTag();
            }
            Log.i("hello",result.toString());
            holder.advice_context.setText(cutContext16(adviceBean.getAdviceList().get(i).getAdviceContent()));
            Log.i("advice_username", adviceBean.getAdviceList().get(i).getUsername());
            holder.username.setText(cutContext6(adviceBean.getAdviceList().get(i).getUsername()));
            Log.i("advice_context", adviceBean.getAdviceList().get(i).getAdviceContent());
            holder.advice_reply.setText(cutContext16(adviceBean.getAdviceList().get(i).getReply()));
            //Log.i("advice_reply", adviceBean.getAdviceList().get(i).getReply());
            return view;
        }
        class ViewHolder{
            TextView username;
            TextView advice_context;
            TextView advice_reply;

        }
    }
    public static void setListViewHeightBasedOnChildren(ListView listView){
        JActivityFragment.AdviceAdapter newsAdapter = (JActivityFragment.AdviceAdapter) listView.getAdapter();
        if (newsAdapter==null){
            return;
        }
        int totalHeight=0;
        //newsAdapter.getCount(); //获取返回数据项的数目
        Log.i("newsAdapter.getCount()",newsAdapter.getCount()+"");
        for (int i=0;newsAdapter.getCount()>i;i++){
            View listItem = newsAdapter.getView(i,null,listView);
            // 计算子项View的宽高
            listItem.measure(0,0);
            // 统计所有子项的总高度
            totalHeight+=listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+(listView.getDividerHeight()*(newsAdapter.getCount()-1));
        //getDividerHeight()：获取子项间分隔符占用的高度， params.height 得到整个ListView 完整显示需要的高度
        Log.i("params.height",params.height+"");
        listView.setLayoutParams(params);
    }
    private String cutContext16(String str) {
        if(str==null){
            return "";
        }
        if (str.length() > 16) {
            String str1 = str.substring(0, 16) + "...";
            return str1;
        } else {
            return str;
        }
    }
    private String cutContext6(String str) {
        if (str.length() > 6){
            String str1 = str.substring(0, 6) + "...";
            return str1;
        } else {
            return str;
        }
    }


}